<template>
  <div class="layout-pd">
    <zh-header-toolbar extra="">
      <zh-button style="margin-left: 6px" v-func:user0027 button-type="add" @click="batchCreateUser">批量生成</zh-button>
      <zh-button style="margin-left: 6px" v-func:user0015 button-type="add" @click="openSystemPrivilegePage">系统级权限分配 </zh-button>
      <zh-button style="margin-left: 6px" v-func:user0019 icon="ele-Avatar" type="primary" @click="openRoleModel">角色分配 </zh-button>
      <zh-button style="margin-left: 6px" v-func:user0021 icon="ele-Calendar" type="primary" @click="openUserRouterFuncModel">资源分配 </zh-button>
      <zh-button style="margin-left: 6px" v-func:user0040 icon="ele-Calendar" type="primary" @click="openUserAppMenuModel">app菜单分配 </zh-button>
      <zh-button style="margin-left: 6px" icon="ele-Share" type="primary" @click="openUserFlowNodeModel"> 流程节点分配 </zh-button>
      <zh-button style="margin-left: 6px" v-func:user0020 icon="ele-EditPen" type="primary" @click="openUserOrgModel">组织分配 </zh-button>
      <zh-button style="margin-left: 6px" v-func:user0001 button-type="add" @click="openAddUser">新增用户</zh-button>
      <zh-button style="margin-left: 6px" v-func:user0026 icon="ele-Refresh" type="warning" @click="refresh">刷新所有用户 </zh-button>
    </zh-header-toolbar>
    <zh-space style="padding-top: 10px">
      <zh-card title="">
        <zh-form ref="userQueryFrom" :model="state.queryParam">
          <zh-form-input
              prop="userName"
              @change="findUserList"
              label="用户名"
              placeholder="支持模糊查询"
              v-model="state.queryParam.userName"
          ></zh-form-input>
          <zh-form-input prop="fullName" label="账号名称" placeholder="支持模糊查询" v-model="state.queryParam.fullName"></zh-form-input>
          <zh-form-input prop="idcard" label="证件号码" placeholder="只能精确查找" v-model="state.queryParam.idcard"></zh-form-input>
          <zh-form-input prop="cellphone" label="手机" placeholder="只能精确查找" v-model="state.queryParam.cellphone"></zh-form-input>
          <zh-form-select
              :disabled="state.userTypeDisabled"
              prop="userTypeList"
              label="用户类型"
              mode="multiple"
              placeholder="支持多选"
              :options="state.dictData.userType"
              v-model="state.queryParam.userTypeList"
          ></zh-form-select>

          <template v-if="state.advanced">
            <zh-form-select
                prop="status"
                label="状态"
                placeholder="单选"
                :options="state.statusData"
                v-model="state.queryParam.status"
            ></zh-form-select>
            <zh-form-select
                placeholder="请搜索，支持多选"
                prop="orgIds"
                funcCode="org0001"
                label="所属组织"
                :timeout="20000"
                searchField="orgName"
                :fieldNames="{
								label: 'orgName',
								value: 'orgId',
							}"
                :lazy="true"
                mode="multiple"
                v-model="state.queryParam.orgIds"
            >
            </zh-form-select>
          </template>
          <zh-form-query v-model="state.advanced" :form-ref="userQueryFrom" :table-ref="userListTable" @queryClick="onQueryTable"></zh-form-query>
        </zh-form>
      </zh-card>
      <zh-table
          ref="userListTable"
          title=""
          :height="600"
          funcCode="user0013"
          :timeout="30000"
          :columns="state.tableColumn"
          @radio-change="radioChangeEvent"
          :radio-config="{ trigger: 'row' }"
          :disabled="false"
          highlight-current-row
          @current-change="handleCurrentChange"
      >
        <template #status_edit="{ row }">
          <el-switch
              v-model="row.status"
              active-text="启用"
              inactive-text="禁用"
              active-value="1"
              inactive-value="0"
              inline-prompt
              size="large"
              @change="onStatusChange(row)"
              :width="50"
          ></el-switch>
        </template>
        <template #resetPassword_default="{ row }">
          <el-button type="danger" @click="resetPasswordEevnt(row.userId)"> 重置 </el-button>
        </template>
        <template #operate_default="{ row }">
          <el-tooltip effect="dark" content="查看用户信息" placement="top">
            <zh-button v-func:user0003 button-type="query" link @click="openQueryUser(row)"></zh-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改用户信息" placement="top">
            <zh-button v-func:user0002 button-type="edit" link @click="openEditUser(row)"></zh-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除用户信息" placement="top">
            <zh-button v-func:user0008 button-type="del" link @click="deleteUser(row)"></zh-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="清除用户缓存" placement="top">
            <zh-button icon="ele-Refresh" type="danger" link @click="clearCache(row)"></zh-button>
          </el-tooltip>
        </template>
      </zh-table>
    </zh-space>
    <zh-dialog :title="state.modalTitle" width="85%" v-model="state.visible" @cancel="cancelUser" @confirm="saveUser">
      <user-form ref="userPage" :dictData="state.dictData" :userInfo="state.userInfo" :showFlag="state.showFlag" />
      <template v-slot:footer>
        <el-button @click="cancelUser"> 关闭 </el-button>
        <el-button type="primary" @click="saveUser" v-if="!state.showFlag"> 保存 </el-button>
      </template>
    </zh-dialog>
    <zh-dialog title="系统级权限授权" width="40%" v-model="state.sysPrivilegeVisible">
      <system-permission-form ref="userSystemPrivilegePage" :userInfo="state.selectRow" />
      <template #footer>
        <div></div>
      </template>
    </zh-dialog>
    <zh-dialog title="角色授权" width="80%" v-model="state.roleVisible">
      <template v-slot:footer>
        <el-button @click="closeRole"> 关闭 </el-button>
        <el-button type="primary" @click="addRole">保存 </el-button>
      </template>
      <RoleUserSelect ref="roleModelPage" :userId="state.userId" v-model="state.roleVisible"/>
    </zh-dialog>
    <zh-dialog title="资源授权" width="40%" v-model="state.roleRouterFuncVisible" @confirm="saveRouterFunc">
      <router-func-tree-form ref="routerFuncTreePage" :userId="state.userId" v-model="state.roleRouterFuncVisible" type="user" />
    </zh-dialog>
    <zh-dialog title="app菜单授权" width="40%" v-model="state.appMenuVisible" @confirm="saveAppMenu">
      <app-menu-tree-form ref="appMenuTreeFormPage" :userId="state.userId" v-model="state.appMenuVisible" type="user" />
    </zh-dialog>
    <zh-dialog title="流程节点授权" width="40%" v-model="state.userFlowNodeVisible" @confirm="saveFlowNode">
      <flow-node-tree-form ref="flowNodeTreePage" :userId="state.userId" v-model="state.userFlowNodeVisible" />
    </zh-dialog>
    <zh-dialog title="组织授权" width="80%" v-model="state.userOrgVisible" @confirm="saveOrg">
      <template v-slot:footer v-if="state.activeNameOrg === 'list'">
        <el-button @click="closeOrg"> 关闭 </el-button>
        <el-button type="primary" @click="addOrg" :disabled="state.saveOrgDisable"> 关联 </el-button>
        <el-button type="danger" @click="deleteOrg" :disabled="state.deleteOrgDisable"> 取消关联 </el-button>
      </template>
      <OrgModule
          ref="orgModelPage"
          @activeNameChange="activeNameChange"
          @searchTypeBtn="setUserOrgBtn"
          :id="state.userId"
          v-model="state.userOrgVisible"
          type="user"
      />
    </zh-dialog>
  </div>
</template>

<script lang="ts" setup name="userManager">
import UserForm from '@/views/system/user/component/UserForm.vue';
import SystemPermissionForm from '@/views/system/user/component/SystemPermissionForm.vue';
import OrgModule from '@/views/system/component/OrgModule.vue';
import RouterFuncTreeForm from '@/views/system/user/component/RouterFuncTreeForm.vue';
import FlowNodeTreeForm from '@/views/system/user/component/FlowNodeTreeForm.vue';
import RoleUserSelect from '@/views/system/user/component/RoleUserSelect.vue';
import AppMenuTreeForm from '@/views/system/user/component/AppMenuTreeForm.vue';
//------------------定义子组件---------------------------
const userQueryFrom = ref<any>({});
const userListTable = ref<any>({});
const userPage = ref<any>({});
const routerFuncTreePage = ref<any>({});
const flowNodeTreePage = ref<any>({});
const orgModelPage = ref<any>({});
const roleModelPage = ref<any>({});
const appMenuTreeFormPage = ref<any>({});

//------------------内部变量定义-------------------------
const state = reactive({
  description: '用户信息管理',
  dictData: {} as any,
  form: null as any,
  orgSelectTreeData: [],
  visible: false,
  showFlag: true,
  userTypeDisabled: false,
  sysPrivilegeVisible: false,
  // 角色授权
  roleVisible: false,
  // 高级搜索 展开/关闭
  advanced: false,
  // 查询参数
  queryParam: {} as any,
  tableData: [] as any[],
  selectRow: {} as any,
  modalTitle: '操作',
  userId: '' as any,
  userOrgVisible: false,
  saveOrgDisable: false,
  deleteOrgDisable: true,
  saveRoleDisable: false,
  deleteRoleDisable: true,
  roleRouterFuncVisible: false,
  appMenuVisible: false,
  userFlowNodeVisible: false,
  opUserId: null as undefined | null | string,
  statusData: [
    { dictKey: '1', dictValue: '启用' },
    { dictKey: '0', dictValue: '禁用' },
  ],
  userInfo: {},
  userType: undefined,
  userTypeList: [],
  // 表头
  tableColumn: [
    {
      type: 'radio',
      width: 40,
      fixed: 'left',
      align: 'center',
    },
    { type: 'seq', width: 60, fixed: 'left', align: 'center', title: '序号' },
    { field: 'userName', title: '用户名', fixed: 'left', align: 'center', width: 150 },
    { field: 'fullName', title: '账号名称', align: 'center', fixed: 'left', width: 150 },
    { field: 'userId', title: '用户Id', visible: false, align: 'center', width: 150 },
    {
      field: 'status',
      title: '状态',
      align: 'center',
      editRender: {},
      slots: {
        // 使用插槽模板渲染
        default: 'status_edit',
        edit: 'status_edit',
      },
      width: 80,
    },
    {
      field: 'resetPassword',
      title: '重置密码',
      align: 'center',
      width: 100,
      slots: {
        default: 'resetPassword_default',
      },
    },
    { field: 'email', title: '电子邮箱', align: 'center', showOverflow: true, width: 150 },
    { field: 'cellphone', title: '手机', align: 'center', width: 150 },
    { field: 'idcard', title: '证件号码', align: 'center', width: 150 },
    { field: 'userType', title: '用户类型key', visible: false, align: 'center', width: 150 },
    { field: 'userTypeName', title: '用户类型', align: 'center', width: 150 },
    { field: 'userIp', title: '使用用户ip', align: 'center', showOverflow: true, width: 200 },
    { field: 'orderNo', title: '顺序', align: 'center', width: 50 },
    { field: 'nikeName', title: '昵称', align: 'center', width: 150 },
    { field: 'sex', title: '性别', visible: false, align: 'center', width: 50 },
    { field: 'sexName', title: '性别', align: 'center', width: 50 },
    { field: 'birthday', title: '出生日期', align: 'center', width: 100 },
    { field: 'address', title: '地址', align: 'center', showOverflow: true, width: 200 },
    { field: 'officePhone', title: '办公室电话', align: 'center', width: 100 },
    { field: 'shortPhone', title: '短号', align: 'center', width: 60 },
    { field: 'orgId', title: '所属组织', visible: false, align: 'center', showOverflow: true, width: 150 },
    { field: 'orgName', title: '所属组织', align: 'center', showOverflow: true, width: 150 },
    { field: 'clientId', title: '所属应用', visible: false, align: 'center', showOverflow: true, width: 150 },
    { field: 'regdate', title: '创建日期', align: 'center', width: 80 },
    { field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 250 },
    { field: 'operate', title: '操作', align: 'center', fixed: 'right', width: 220, slots: { default: 'operate_default' } },
  ],
  activeNameOrg: 'list',
});

//------------------定义调用方法-------------------------
function activeNameChange(name) {
  state.activeNameOrg = name;
}
function batchCreateUser() {
  const params = {};
  setTimeout(() => {
    $api.common.send
        .post('user0027', params)
        .then((res) => {
          $messageBox.success('成功生成' + res.result + '个用户', '提示');
        })
        .catch(() => {});
  }, 200);
}
function refresh() {
  const params = {};
  setTimeout(() => {
    $api.common.send
        .post('user0038', params)
        .then(() => {
          $messageBox.success('刷新成功', '提示');
        })
        .catch(() => {});
  }, 200);
}
function openSystemPrivilegePage() {
  console.log(state.userId);
  if (state.userId) {
    if (state.opUserId == state.userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    state.sysPrivilegeVisible = true;
  } else {
    $messageBox.warning('请先选择需要修改的数据', '提示');
  }
}
function openRoleModel() {
  if (state.userId) {
    if (state.opUserId == state.userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    state.roleVisible = true;
  } else {
    $messageBox.warning('请先选择需要授权的数据', '提示');
  }
}
function openUserRouterFuncModel() {
  // 打开资源授权页面
  if (state.userId) {
    if (state.opUserId == state.userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    state.roleRouterFuncVisible = true;
  } else {
    $messageBox.warning('请先选择需要操作的用户', '提示');
  }
}
function openUserAppMenuModel() {
  // 打开资源授权页面
  if (state.userId) {
    if (state.opUserId == state.userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    state.appMenuVisible = true;
  } else {
    $messageBox.warning('请先选择需要操作的用户', '提示');
  }
}
function openUserFlowNodeModel() {
  // 打开节点授权页面
  if (state.userId) {
    if (state.opUserId == state.userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    state.userFlowNodeVisible = true;
  } else {
    $messageBox.warning('请先选择需要操作的用户', '提示');
  }
}

function openUserOrgModel() {
  // 打开组织授权页面
  if (state.userId) {
    if (state.opUserId == state.userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    state.userOrgVisible = true;
  } else {
    $messageBox.warning('请先选择需要操作的用户', '提示');
  }
}
function openAddUser() {
  clearRadioRowEevnt();
  let userInfo = {
    userType: state.userType,
  };
  state.userInfo = userInfo;
  state.modalTitle = '新增用户信息';
  state.visible = true;
  state.showFlag = false;
}
function clearRadioRowEevnt() {
  state.selectRow = {} as any;
  state.userId = undefined;
  userListTable.value.clearRadioRow();
}
function openQueryUser(row) {
  let userInfo = {
    userType: row.userType,
    userId: row.userId,
  };
  state.userInfo = userInfo;
  state.modalTitle = '查看用户信息';
  state.visible = true;
  state.showFlag = true;
}
function openEditUser(row) {
  if (row.userId) {
    let userInfo = {
      userType: row.userType,
      userId: row.userId,
    };
    state.userInfo = userInfo;
    state.modalTitle = '修改用户信息';
    state.visible = true;
    state.showFlag = false;
  } else {
    $messageBox.warning('请先选择需要修改的数据', '提示');
  }
}
function deleteUser(row) {
  if (row.userId) {
    const params = {
      userId: row.userId,
    };
    setTimeout(() => {
      $api.common.send
          .post('user0008', params)
          .then(() => {
            $messageBox.success('删除用户成功', '提示');
            refreshList();
          })
          .catch(() => {});
    }, 100);
  } else {
    $messageBox.warning('请先选择需要删除的数据', '提示');
  }
}
function clearCache(row) {
  if (row.userId) {
    const params = {
      userId: row.userId,
    };
    setTimeout(() => {
      $api.common.send
          .post('user0026', params)
          .then(() => {
            $messageBox.success('清除该用户缓存成功', '提示');
            findUserList();
          })
          .catch(() => {});
    }, 100);
  } else {
    $messageBox.warning('请先选择需要清除缓存的数据', '提示');
  }
}
function findUserList() {
  state.selectRow = null;
  state.userId = null;
  userListTable.value.query(state.queryParam);
}
function refreshList() {
  state.selectRow = null;
  state.userId = null;
  userListTable.value.refresh(state.queryParam);
}
function radioChangeEvent({ row }) {
  state.selectRow = row;
  state.userId = row.userId;
}
// 启用/禁用用户
function onStatusChange(row) {
  if (!row.userId) {
    return;
  }
  if (state.opUserId === row.userId) {
    row.status = !row.status;
    $messageBox.warning('不能对自己进行操作', '提示');
    return;
  }
  const params = {
    userId: row.userId,
    status: row.status,
  };
  let text = '禁用';
  if (row.status === '1') {
    text = '启用';
  }
  $api.common.send
      .postCrypto('user0007', params)
      .then(() => {
        $messageBox.success(text + '成功', '提示');
      })
      .catch(() => {
        row.status = !params.status;
      });
}

async function saveUser() {
  let res = await userPage.value.saveUser();
  if (res && res.code === 0) {
    state.visible = false;
    state.queryParam.userName = res.result.userName;
    findUserList();
  }
}

function cancelUser() {
  state.visible = false;
}

// 重置密码
function resetPasswordEevnt(userId) {
  if (userId) {
    if (state.opUserId == userId) {
      $messageBox.warning('不能对自己进行操作', '提示');
      return;
    }
    const params = {
      userId: userId,
      passwordType: '1',
    };
    $api.common.send
        .postCrypto('user0004', params)
        .then((res) => {
          $messageBox.success('重置成功！密码为' + res.result, '提示');
        })
        .catch(() => {});
  } else {
    $messageBox.error('程序异常，未传入用户Id字段', '提示');
  }
}
function onQueryTable() {
  state.selectRow = null;
  state.userId = null;
}
function handleCurrentChange(row) {
  state.selectRow = row;
  state.userId = row.userId;
}

function saveRouterFunc() {
  routerFuncTreePage.value.saveRouterFunc('user');
}
function saveAppMenu() {
  appMenuTreeFormPage.value.saveAppRouter('user');
}

//保存用户节点授权数据
function saveFlowNode() {
  flowNodeTreePage.value.saveFlowNode('user');
}
function setUserOrgBtn(value) {
  if (value) {
    if (value === '1') {
      state.saveOrgDisable = false;
      state.deleteOrgDisable = true;
    } else if (value === '2') {
      state.saveOrgDisable = true;
      state.deleteOrgDisable = false;
    }
    if (value === '3') {
      state.saveOrgDisable = true;
      state.deleteOrgDisable = true;
    }
  } else {
    state.saveOrgDisable = false;
    state.deleteOrgDisable = true;
  }
}

function addOrg() {
  orgModelPage.value.add();
}
function saveOrg() {
  orgModelPage.value.save();
}
function deleteOrg() {
  orgModelPage.value.del();
}
function closeOrg() {
  state.userOrgVisible = false;
}
function addRole() {
  roleModelPage.value.save();
}
function closeRole() {
  state.roleVisible = false;
}
//------------------初始化------------------------------

//获取路由配置中param1参数
let meta = useRouter().currentRoute.value.meta;
if (meta && meta.query) {
  const query: any = meta.query;
  if (query.userType) {
    state.queryParam.userType = query.userType;
    state.userType = query.userType;
    let userTypeList: any[] = [];
    userTypeList.push(query.userType);
    state.queryParam.userTypeList = userTypeList;
    state.userTypeDisabled = true;
  }
  if (query.userTypeList && query.userTypeList.length > 0) {
    state.queryParam.userTypeList = query.userTypeList;
    state.userTypeList = query.userTypeList;
    if (query.userTypeList.length === 1) {
      state.userTypeDisabled = true;
    } else {
      state.userTypeDisabled = false;
    }
  }
}
// 数据字典初始化
const params = {
  dictFields: 'userType,sex,cardType',
};
$api.common.getBatchDict.post(params).then((res) => {
  let result=res.result
  console.log(result)
  if(result.userType&&state.userTypeList && state.userTypeList.length > 0){
    console.log(result.userType)
    let userTypeListFilter=[] as any;
    result.userType.forEach(element => {
      if(state.userTypeList.some(item=>item===element.dictKey)){
        userTypeListFilter.push(element);
      }
    });
    result.userType=userTypeListFilter;
  }
  state.dictData = result;


});
state.opUserId = $store.user.userInfo?.userId;
// 初始化人员列表
onMounted(() => {
  nextTick(() => {
    findUserList();
  });
});
</script>